初次探索java注解(Annotation)

JavaSE 自带的注解

我们可以自定义一个类,其中定义了一个方法,并用Deprecated注解去标注该方法已经过时,可以看到在main方法中调用该方法会报出警告.

1
2
3
4
5
6
7
8
9
10
11
public class AnnotationDemo1 {

public static void main(String[] args) {
//此时可以看出下面这句语句编译器是发出警告的
test1();
}

@Deprecated
public static void test1(){}

}

但是用到java.lang包下的@SuppressWarnings注解就可以消除该警告:

1
2
3
4
5
6
7
8
9
10
11
12
public class AnnotationDemo1 {

@SuppressWarnings("deprecation")
public static void main(String[] args) {
//此时警告消除
test1();
}

@Deprecated
public static void test1(){}

}

自定义注解实战

1.获取注解的信息

我们可以使用Intellij IDEA快速生成注解:

自定义注解类代码如下:
Description.java

1
2
3
4
5
6
7
8
9
import java.lang.annotation.*;

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Description {
String value();
}

引用注解类代码如下:
MyAnn1.java

1
2
3
4
5
6
7
8
9
10
11
12
@Description("I am class annotation")
public class MyAnn1 {

//这里会报错: @Description is nuo applicable to field,因为在定义注解时候我们没有在@Target中去定义field目标.所以我们
@Description("I am field annotation")
private String testField;

@Description("I am method annotation")
public String name() {
return null;
}
}

我们再写一个解析处理器去处理这些注解信息,其中main方法入口也在这里:

处理自定义注解的步骤:

  1. 首先用java 提供的反射方法获取类加载器
  2. 使用getAnnotation找到类下的注解,并获取其中已经定义的值.
  3. 再用类加载器的方法获取所有method,遍历判断是否有注解并获取到注解,从而获取到值.
    ParseAnn.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.lang.reflect.Method;

public class ParseAnn {

public static void main(String[] args) {
try {
//首先用java 提供的反射方法获取类加载器
Class<?> clazz = Class.forName("diy.MyAnn1");//这里需要注意加上包名不然会抛异常
if (clazz.isAnnotationPresent(Description.class)) {
//获取到类注解
Description description = clazz.getAnnotation(Description.class);
System.out.println(description.value());//value()方法就是定义在注解类中的一个方法.
}
//获取方法下的类注解
Method[] methods = clazz.getMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(Description.class)) {
Description description = method.getAnnotation(Description.class);
System.out.println(description.value());
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

}

然后运行,可以看到程序运行结果和预想的一样:

1
2
I am class annotation
I am method annotation

后续更新中….